package com.yio.wifi;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import java.util.Comparator;
import java.util.List;

public class WifiAdmin {
    private static final String TAG = "WifiAdmin";
    /** * 定义一个WifiManager对象,提供Wifi管理的各种主要API
     ，主要包含wifi的扫描、建立连接、配置信息等 */
    private WifiManager mWifiManager;


    // WIFIConfiguration描述WIFI的链接信息，包括SSID、SSID隐藏、password等的设置
    private List<WifiConfiguration> wifiConfigList;

    // 定义一个WifiInfo对象

    private WifiInfo mWifiInfo;

    // 扫描出的网络连接列表
    private List<ScanResult> mWifiList;

    WifiManager.WifiLock mWifiLock;

    public static final int TYPE_NO_PASSWD = 0x11;
    public static final int TYPE_WEP       = 0x12;
    public static final int TYPE_WPA       = 0x13;
    private NetworkInfo wifiNetworkInfo;
    public WifiAdmin(Context context) {
        // 获得WifiManager对象
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    }

    /** * 打开wifi */
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    /** * 关闭wifi */
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }


    public boolean isWifiConnected()
    {
        return wifiNetworkInfo.isConnected() ;
    }

    /** * 检查当前wifi状态 * *
     @return */
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    /** * 锁定wifiLock */
    public void acquireWifiLock() {

        mWifiLock.acquire();
    }

    /** * 解锁wifiLock */
    public void releaseWifiLock()
    {
        // 判断是否锁定
        if (mWifiLock.isHeld()) {

            mWifiLock.acquire();
        }
    }

    /** * 创建一个wifiLock */
    public void createWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("test");
    }


    /** * 得到配置好的网络 * * @return */
    public List<WifiConfiguration> getWiFiConfiguration() {
        return wifiConfigList;
    }

    /** * 指定配置好
     的网络进行连接 * * @param index */
    public void connetionConfiguration(int index)
    {
        if (index > wifiConfigList.size()) {
            return;
        }
        // 连接配置好指定ID的网络
        mWifiManager.enableNetwork(wifiConfigList.get(index).networkId, true);
    }

    public void startScan() {
        mWifiManager.startScan();
        // 得到扫描结果
        mWifiList = mWifiManager.getScanResults();
        // 得到配置好的网络连接
        wifiConfigList = mWifiManager.getConfiguredNetworks();

        getConnectionInfo();
    }

    public void getConnectionInfo() {
        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    /** *
     得到网络列表 * * @return */
    public List<ScanResult> getWifiList() {
        return mWifiList;
    }

    /** * 查看扫描结果 * * @return */
    public StringBuffer lookUpScan() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mWifiList.size(); i++) {
            sb.append("Index_" + Integer.valueOf(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包
            //其中把包括：BSSID、SSID、capabilities、frequency、level
            sb.append((mWifiList.get(i)).toString())
              .append("\n");
        }
        return sb;
    }


    public String getMacAddress() {
        return (mWifiInfo == null)
               ? "NULL"
               : mWifiInfo.getMacAddress();
    }

    public String getBSSID() {
        return (mWifiInfo == null)
               ? "NULL"
               : mWifiInfo.getBSSID();
    }

    public int getIpAddress() {
        return (mWifiInfo == null)
               ? 0
               : mWifiInfo.getIpAddress();

    }

    /** * 得到连接的ID * * @return */
    public int getNetWorkId() {
        return (mWifiInfo == null)
               ? 0
               : mWifiInfo.getNetworkId();
    }

    /** * 得到连接的SSID * * @return */
    public String getSSID() {
        return (mWifiInfo == null)
               ? null
               : mWifiInfo.getSSID().replace("\"","");
    }

    /** * 得到wifiInfo的所有
     信息 * * @return */
    public String getWifiInfo() {
        return (mWifiInfo == null)
               ? "NULL"
               : mWifiInfo.toString();
    }

    /** * 添加一个网络并连接 * * @param
     configuration */
    public int addNetwork(WifiConfiguration configuration) {
        return mWifiManager.addNetwork(configuration);
    }

    public WifiConfiguration createWifiInfo(String SSID, String Password,

                                            int Type)
    {
        WifiConfiguration config = new WifiConfiguration();

        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";


        WifiConfiguration tempConfig = this.isExsits(SSID);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }


        if (Type == 1) // WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = "\"\"";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) // WIFICIPHER_WEP
        {

            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password +
                    "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 3) // WIFICIPHER_WPA
        {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    private WifiConfiguration isExsits(String ssid) {
        WifiConfiguration config = null;

        if (mWifiList.size() > 0) {
            for (int i = 0; i < wifiConfigList.size(); i++) {
                if (wifiConfigList.get(i).SSID.equals(ssid)) {
                    config = wifiConfigList.get(i);
                }
            }
        }
        return config;
    }

    /** * 断开wifi连接 * * @param netId */

    public void disConnectionWifi() {
        mWifiManager.disconnect();
    }

    public void removeNetwork(int netId) {
        mWifiManager.removeNetwork(netId);
    }

    /*
     * 连接指定Id的WIFI
     * @param wifiId
     * @return
     */
    public boolean ConnectWifi(int wifiId) {

        /*for (int i = 0; i < wifiConfigList.size(); i++) {
            WifiConfiguration wifi = wifiConfigList.get(i);
            if (wifi.networkId == wifiId) {

                while (!(mWifiManager.enableNetwork(wifiId, true))) {
                    // 激活该Id，建立连接
                    Log.i("ConnectWifi",
                          String.valueOf(wifiConfigList.get(wifiId).status));// status:0--已经连接，1--不可连接，2--可以连接

                }
                return true;
            }
        }
        return false;*/
        return mWifiManager.enableNetwork(wifiId, true);
    }

    /** * 得到Wifi配置好的信息 */
    public List<WifiConfiguration> getConfiguration() {

        wifiConfigList = mWifiManager.getConfiguredNetworks();// 得到配置好的网络信息
        /*if(wifiConfigList != null)
        for (int i = 0; i < wifiConfigList.size(); i++) {
            L.e("getConfiguration", wifiConfigList.get(i).SSID);
            L.e("getConfiguration", String.valueOf(wifiConfigList.get(i).networkId));
        }*/
        return wifiConfigList;
    }

    /** * 判定指定WIFI是否已经配置好,依据WIFI的地址
     BSSID,返回NetId * * @param SSID * @return */
    public int IsConfiguration(String SSID) {

        for (int i = 0; i < wifiConfigList.size(); i++) {
            Log.i(wifiConfigList.get(i).SSID, String.valueOf(wifiConfigList.get(i).networkId));
            if (wifiConfigList.get(i).SSID.equals(SSID)) {
                // 地址相同
                return wifiConfigList.get(i).networkId;
            }
        }

        return -1;
    }

    /**
     *  添加指定WIFI的配置信息,原列表不存在此SSID *
     *  @param wifiList
     *  @param ssid
     *  @param pwd
     *  @return
     *  */
    public int AddWifiConfig(List<ScanResult> wifiList, String ssid, String pwd) {
        int wifiId = -1;

        for (int i = 0; i < wifiList.size(); i++) {
            ScanResult wifi = wifiList.get(i);
            if (wifi.SSID.equals(ssid)) {
                Log.i("AddWifiConfig", "equals");
                WifiConfiguration wifiCong = new WifiConfiguration();
                wifiCong.SSID = "\"" + wifi.SSID + "\"";
                // \"转义字符，代表"
                wifiCong.preSharedKey = "\"" + pwd + "\"";// WPA-PSK密码
                wifiCong.hiddenSSID = false;
                wifiCong.status = WifiConfiguration.Status.ENABLED;
                wifiId = mWifiManager.addNetwork(wifiCong);
                // 将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态，成功返回ID，否则为-1
                if (wifiId != -1) {
                    return wifiId;

                }
            }
        }
        return wifiId;
    }

    // Constants used for different security types
    public static final String WPA2 = "WPA2";
    public static final String WPA = "WPA";
    public static final String WEP = "WEP";
    public static final String OPEN = "Open";
    // For EAP Enterprise fields
    public static final String WPA_EAP = "WPA-EAP";
    public static final String IEEE8021X = "IEEE8021X";

    public static final String[] EAP_METHOD = { "PEAP", "TLS", "TTLS" };

    public static final int WEP_PASSWORD_AUTO = 0;
    public static final int WEP_PASSWORD_ASCII = 1;
    public static final int WEP_PASSWORD_HEX = 2;


    /**
     * Change the password of an existing configured network and connect to it
     * @param wifiMgr
     * @param config
     * @param newPassword
     * @return
     */
    public static boolean changePasswordAndConnect( final WifiManager wifiMgr, final WifiConfiguration config, final String newPassword, final int numOpenNetworksKept) {
        setupSecurity(config, getWifiConfigurationSecurity(config), newPassword);
        final int networkId = wifiMgr.updateNetwork(config);
        if(networkId == -1) {
            // Update failed.
            return false;
        }
        //确定
        return connectToConfiguredNetwork(wifiMgr, config, true);
    }

    /**
     * Configure a network, and connect to it.
     * @param wifiMgr
     * @param scanResult
     * @param password Password for secure network or is ignored.
     * @return
     */
    public static boolean connectToNewNetwork(final WifiManager wifiMgr, final ScanResult scanResult, final String password) {
        //1.获取wifi加密方式（WEP, WPA, WPA2, WPA_EAP, IEEE8021X）
        final String security = getScanResultSecurity(scanResult);

        if(security.equals(OPEN)) {
            final int numOpenNetworksKept = 10;
            checkForExcessOpenNetworkAndSave(wifiMgr, numOpenNetworksKept);
        }

        WifiConfiguration config = new WifiConfiguration();
        config.SSID = StringUtils.convertToQuotedString(scanResult.SSID);
        config.BSSID = scanResult.BSSID;
        setupSecurity(config, security, password);

        int id = wifiMgr.addNetwork(config);
        if(id == -1) {
            return false;
        }

        if(!wifiMgr.saveConfiguration()) {
            return false;
        }

        config = getWifiConfiguration(wifiMgr, config, security);
        if(config == null) {
            return false;
        }

        return connectToConfiguredNetwork(wifiMgr, config, true);
    }

    /**
     * Connect to a configured network.
     */
    public static boolean connectToConfiguredNetwork( final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) {
        final String security = getWifiConfigurationSecurity(config);

        int oldPri = config.priority;
        // Make it the highest priority.
        int newPri = getMaxPriority(wifiMgr) + 1;
        if(newPri > MAX_PRIORITY) {
            newPri = shiftPriorityAndSave(wifiMgr);
            config = getWifiConfiguration(wifiMgr, config, security);
            if(config == null) {
                return false;
            }
        }

        // Set highest priority to this configured network
        config.priority = newPri;
        int networkId = wifiMgr.updateNetwork(config);
        if(networkId == -1) {
            return false;
        }

        // Do not disable others
        if(!wifiMgr.enableNetwork(networkId, false)) {
            config.priority = oldPri;
            return false;
        }

        if(!wifiMgr.saveConfiguration()) {
            config.priority = oldPri;
            return false;
        }

        // We have to retrieve the WifiConfiguration after save.
        config = getWifiConfiguration(wifiMgr, config, security);
        if(config == null) {
            return false;
        }

        // Disable others, but do not save.
        // Just to force the WifiManager to connect to it.
        if(!wifiMgr.enableNetwork(config.networkId, true)) {
            return false;
        }

        final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect();
        if(!connect) {
            return false;
        }

        return true;
    }

    private static void sortByPriority(final List<WifiConfiguration> configurations) {
        java.util.Collections.sort(configurations, new Comparator<WifiConfiguration>() {

            @Override
            public int compare(WifiConfiguration object1,
                               WifiConfiguration object2) {
                return object1.priority - object2.priority;
            }
        });
    }

    /**
     * Ensure no more than numOpenNetworksKept open networks in configuration list.
     * @param wifiMgr
     * @param numOpenNetworksKept
     * @return Operation succeed or not.
     */
    private static boolean checkForExcessOpenNetworkAndSave(final WifiManager wifiMgr, final int numOpenNetworksKept) {
        final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
        sortByPriority(configurations);

        boolean modified = false;
        int tempCount = 0;
        for(int i = configurations.size() - 1; i >= 0; i--) {
            final WifiConfiguration config = configurations.get(i);
            if(getWifiConfigurationSecurity(config).equals(OPEN)) {
                tempCount++;
                if(tempCount >= numOpenNetworksKept) {
                    modified = true;
                    wifiMgr.removeNetwork(config.networkId);
                }
            }
        }
        if(modified) {
            return wifiMgr.saveConfiguration();
        }

        return true;
    }

    private static final int MAX_PRIORITY = 99999;

    private static int shiftPriorityAndSave(final WifiManager wifiMgr) {
        final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
        sortByPriority(configurations);
        final int size = configurations.size();
        for(int i = 0; i < size; i++) {
            final WifiConfiguration config = configurations.get(i);
            config.priority = i;
            wifiMgr.updateNetwork(config);
        }
        wifiMgr.saveConfiguration();
        return size;
    }

    private static int getMaxPriority(final WifiManager wifiManager) {
        final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
        int pri = 0;
        for(final WifiConfiguration config : configurations) {
            if(config.priority > pri) {
                pri = config.priority;
            }
        }
        return pri;
    }

    public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr,
                                                         final ScanResult hotsopt, String hotspotSecurity) {
        final String ssid = StringUtils.convertToQuotedString(hotsopt.SSID);
        if(ssid.length() == 0) {
            return null;
        }

        final String bssid = hotsopt.BSSID;
        if(bssid == null) {
            return null;
        }

        if(hotspotSecurity == null) {
            hotspotSecurity = getScanResultSecurity(hotsopt);
        }

        final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();

        for(final WifiConfiguration config : configurations) {
            if(config.SSID == null || !ssid.equals(config.SSID)) {
                continue;
            }
            if(config.BSSID == null || bssid.equals(config.BSSID)) {
                final String configSecurity = getWifiConfigurationSecurity(config);
                if(hotspotSecurity.equals(configSecurity)) {
                    return config;
                }
            }
        }
        return null;
    }

    public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr,
                                                         final WifiConfiguration configToFind, String security) {
        final String ssid = configToFind.SSID;
        if(ssid.length() == 0) {
            return null;
        }

        final String bssid = configToFind.BSSID;


        if(security == null) {
            security = getWifiConfigurationSecurity(configToFind);
        }

        final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();

        for(final WifiConfiguration config : configurations) {
            if(config.SSID == null || !ssid.equals(config.SSID)) {
                continue;
            }
            if(config.BSSID == null || bssid == null || bssid.equals(config.BSSID)) {
                final String configSecurity = getWifiConfigurationSecurity(config);
                if(security.equals(configSecurity)) {
                    return config;
                }
            }
        }
        return null;
    }

    /**
     * @return The security of a given {@link WifiConfiguration}.
     */
    static public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) {

        if (wifiConfig.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
            // If we never set group ciphers, wpa_supplicant puts all of them.
            // For open, we don't set group ciphers.
            // For WEP, we specifically only set WEP40 and WEP104, so CCMP
            // and TKIP should not be there.
            if (!wifiConfig.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.CCMP)
                    && (wifiConfig.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.WEP40)
                    || wifiConfig.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.WEP104))) {
                return WEP;
            } else {
                return OPEN;
            }
        } else if (wifiConfig.allowedProtocols.get(WifiConfiguration.Protocol.RSN)) {
            return WPA2;
        } else if (wifiConfig.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)) {
            return WPA_EAP;
        } else if (wifiConfig.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
            return IEEE8021X;
        } else if (wifiConfig.allowedProtocols.get(WifiConfiguration.Protocol.WPA)) {
            return WPA;
        } else {
            Log.w(TAG, "Unknown security type from WifiConfiguration, falling back on open.");
            return OPEN;
        }
    }

    /**
     * Fill in the security fields of WifiConfiguration config.
     * @param config The object to fill.
     * @param security If is OPEN, password is ignored.
     * @param password Password of the network if security is not OPEN.
     */
    static private void setupSecurity(WifiConfiguration config, String security, final String password) {
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();

        if (TextUtils.isEmpty(security)) {
            security = OPEN;
            Log.w(TAG, "Empty security, assuming open");
        }

        if (security.equals(WEP)) {
            int wepPasswordType = WEP_PASSWORD_AUTO;
            // If password is empty, it should be left untouched
            if (!TextUtils.isEmpty(password)) {
                if (wepPasswordType == WEP_PASSWORD_AUTO) {
                    if (isHexWepKey(password)) {
                        config.wepKeys[0] = password;
                    } else {
                        config.wepKeys[0] = StringUtils.convertToQuotedString(password);
                    }
                } else {
                    config.wepKeys[0] = wepPasswordType == WEP_PASSWORD_ASCII
                            ? StringUtils.convertToQuotedString(password)
                            : password;
                }
            }

            config.wepTxKeyIndex = 0;

            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);

            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

        } else if (security.equals(WPA) || security.equals(WPA2)){
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);

            config.allowedProtocols.set(security.equals(WPA2) ? WifiConfiguration.Protocol.RSN : WifiConfiguration.Protocol.WPA);

            // If password is empty, it should be left untouched
            if (!TextUtils.isEmpty(password)) {
                if (password.length() == 64 && isHex(password)) {
                    // Goes unquoted as hex
                    config.preSharedKey = password;
                } else {
                    // Goes quoted as ASCII
                    config.preSharedKey = StringUtils.convertToQuotedString(password);
                }
            }

        } else if (security.equals(OPEN)) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        } else if (security.equals(WPA_EAP) || security.equals(IEEE8021X)) {
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            if (security.equals(WPA_EAP)) {
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
            } else {
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
            }
            if (!TextUtils.isEmpty(password)) {
                config.preSharedKey = StringUtils.convertToQuotedString(password);
            }
        }
    }

    private static boolean isHexWepKey(String wepKey) {
        final int len = wepKey.length();

        // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
        if (len != 10 && len != 26 && len != 58) {
            return false;
        }

        return isHex(wepKey);
    }

    private static boolean isHex(String key) {
        for (int i = key.length() - 1; i >= 0; i--) {
            final char c = key.charAt(i);
            if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) {
                return false;
            }
        }

        return true;
    }

    static final String[] SECURITY_MODES = { WEP, WPA, WPA2, WPA_EAP, IEEE8021X };

    /**
     * @return The security of a given {@link ScanResult}.
     */
    public static String getScanResultSecurity(ScanResult scanResult) {
        final String cap = scanResult.capabilities;
        for (int i = SECURITY_MODES.length - 1; i >= 0; i--) {
            if (cap.contains(SECURITY_MODES[i])) {
                return SECURITY_MODES[i];
            }
        }

        return OPEN;
    }
}